// pages/facility/facility.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {
  API_CONFIRM_BINDING_PASTE,
  API_CONFIRM_UNBINDING_PASTE
} from '../../api/index'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bindFacilityData: {},
    userInfo: {}, // 微信用户数据
    isVisitor: false,
    deviceId: '',
    deviceDatas: [], // 设备数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const bindFacilityData = wx.getStorageSync('bindFacilityData'),
      isVisitor = wx.getStorageSync('isVisitor')
    this.setData({
      isVisitor,
      userInfo: wx.getStorageSync('userInfo'),
      bindFacilityData,
      deviceDatas: bindFacilityData.tppaste != 0 && !isVisitor ? [{
        tpcode: bindFacilityData.tpcode,
        tpname: bindFacilityData.tpname,
      }] : []
    })
  },

  onUnload: function () {
    wx.setStorageSync('bindFacilityData', {})
    wx.setStorageSync('isVisitor', false)
    // 关闭蓝牙搜索
    wx.stopBluetoothDevicesDiscovery({
      success: res => {
        console.log('关闭蓝牙搜索');
      }
    })
  },
  // 绑定体温贴
  onBingFacility(e) {
    console.log(e)
    const params = {
      open_id: wx.getStorageSync('openId'),
      username: this.data.isVisitor ? this.data.userInfo.nickName : this.data.bindFacilityData.username,
      idcardno: this.data.bindFacilityData.idcardno,
      tpname: e.currentTarget.dataset.item.tpname,
      tpcode: e.currentTarget.dataset.item.tpcode,
      tourist: this.data.bindFacilityData.sort == 8 || this.data.isVisitor ? 'Y' : '',
      userid: this.data.isVisitor ? 'undefined' : this.data.bindFacilityData.userid + ''
    }
    // 连接蓝牙设备
    // this.connetBlue(e.currentTarget.dataset.item.tpcode);
    API_CONFIRM_BINDING_PASTE(params).then(res => {
      if (res.code == 200) {
        wx.showToast({
          title: '绑定成功',
        })
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }, 2000)
      }
    })
  },

  // 解绑体温贴
  onUnBingFacility() {
    const params = {
      unbundlingType: 'Y',
      tourist: this.data.bindFacilityData.sort == 8 ? 'Y' : "",
      open_id: wx.getStorageSync('openId'),
      username: this.data.bindFacilityData.username,
      idcardno: this.data.bindFacilityData.idcardno,
      tpcode: this.data.bindFacilityData.tpcode,
    }
    API_CONFIRM_UNBINDING_PASTE(params).then(res => {
      if (res.code == 200) {
        wx.showToast({
          title: '解绑成功',
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }
    })
  },

  startNFC () {
    const that = this
    const nfc = wx.getNFCAdapter()
    
    nfc.onDiscovered(res => {
      // 设备id
      console.log(this.ab2hex(res.id))

      const nfca = nfc.getNfcA()

      // 链接设备
      nfca.connect({
        success () {
          // // 开启设备
          // nfca.transceive({
          //   data: that.string2buffer('40c00600000000'),
          //   success (res) {
          //     if (that.ab2hex(res.data) === '00faff') {
          //       console.log(res)
          //     }
          //   },
          //   fail (err) {
          //     console.log(err)
          //   }
          // })

          // 测温
          nfca.transceive({
            data: that.string2buffer('40c08400000000'),
            success (res) {
              // 温度
              const tp = that.getTp(that.ab2hex(res.data))
              console.log(tp)
            },
            fail (err) {
              console.log(err)
              }
          })
        }
      })
    })
    nfc.startDiscovery({
      success () {
        wx.showToast({
          title: '请将设备放入NFC识别区',
        })
      },
      fail (err) {
        console.log(err)
        if (err.errCode === 13021) return
        Dialog.confirm({
          title: '初始化NFC模块失败，请检查NFC是否已开启',
          showCancelButton: false,
          confirmButtonText: '知道了'
        })
      }
    })
  },

  /**
   * 初始化蓝牙设备
   */
  initBlue() {
    wx.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
      success: res => {
        // console.log(res)
        // wx.showToast({
        //   title: '初始化成功',
        //   icon: 'success',
        //   duration: 800
        // })
        this.findBlue();
      },
      fail: res => { //如果手机上的蓝牙没有打开，可以提醒用户
        Dialog.confirm({
          title: '请开启手机蓝牙功能, 以连接配件',
          showCancelButton: false,
          confirmButtonText: '知道了'
        })
      }
    })
  },

  /**
   *开始搜索蓝牙设备
   */
  findBlue() {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: res => {
        wx.showLoading({
          title: '正在搜索设备',
        })
        this.getBlue()
      }
    })
  },

  /**
   * 获取搜索到的设备信息
   */
  getBlue() {
    this.setData({
      deviceDatas: []
    })
    wx.getBluetoothDevices({
      success: res => {
        console.log(res.devices)
        for (var i = 0; i < res.devices.length; i++) {
          //this.data.deviceId：
          /**表示的是需要连接的蓝牙设备ID，简单点来说就是我想要连接这个蓝牙设备，
          所以我去遍历我搜索到的蓝牙设备中是否有这个ID
          */
          if (res.devices[i].name.indexOf('EFS') != -1) {
            this.setData({
              deviceDatas: [...this.data.deviceDatas, {
                tpcode: res.devices[i].deviceId,
                tpname: res.devices[i].name,
              }]
            })
          }
        }
        if (this.data.deviceDatas.length == 0) this.getBlue()
        else wx.hideLoading();
      },
      fail: function () {
        console.log("搜索蓝牙设备失败")
      }
    })
  },
  string2buffer(str) {
    let val = ""
    if(!str) return;
    let length = str.length;
    let index = 0;
    let array = []
    while(index < length){
      array.push(str.substring(index,index+2));
      index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  getTp (hex) {
    let res = hex.slice(-4)
    res = (res.slice(-2) + res).slice(0, 4)
    console.log(res)
    let revert2Bytes = ('0000000000000000' + parseInt(res, 16).toString(2)).slice(-16)
    console.log(revert2Bytes)
    let symbol = parseInt(revert2Bytes[6])
    console.log(symbol)
    res = parseInt(revert2Bytes.slice(7), 2)
    if (symbol === 0) {
      return res / 4
    } else {
      return (0x1ff - res + 1) / 4
    }
  }
})